﻿using System;
using System.Collections.Generic;
using Present.Commands.Async.Actions;
using Present.Commands.Async.Actions.Decorators;

namespace Present.Commands.Fluent
{
    public class CompositeAsyncActionBuilder : ActionBuilder<object, object>
    {
        private readonly List<IObservableCommandAction> actions = new List<IObservableCommandAction>();
        private Action<object> whenFinishedAction = x=> { };
        private Action<Exception> handleErrorAction;

      
        /// <summary>
        /// Add another Action to run asyncronoushly
        /// </summary>
        public CompositeAsyncActionBuilder Add(IObservableCommandAction action)
        {
            this.actions.Add(action);
            return this;
        }

        /// <summary>
        /// Add numerous Actions to run asyncronoushly
        /// </summary>
        public CompositeAsyncActionBuilder AddRange(IEnumerable<IObservableCommandAction> newActions)
        {
            actions.AddRange(newActions);
            return this;
        }

        /// <summary>
        /// Runs the action when all AsyncActions have completed
        /// </summary>
        public CompositeAsyncActionBuilder WhenAllFinished(Action<object> whenFinished)
        {
            this.whenFinishedAction = whenFinished;
            return this;
        }


        /// <summary>
        /// Error handler
        /// </summary>
        public CompositeAsyncActionBuilder HandleError(Action<Exception> handleError)
        {
            this.handleErrorAction = handleError;
            return this;
        }

   
        public static implicit operator CompositeAsyncAction(CompositeAsyncActionBuilder builder)
        {
            return new CompositeAsyncAction(builder.whenFinishedAction, builder.handleErrorAction, builder.actions.ToArray());
        }

        protected override IAsyncAction<object, object> GetAction()
        {
            return (CompositeAsyncAction) this;
        }

      
    }
}